#coding=utf-8
import urllib2,cookielib,urllib,HTMLParser
'''
	MyWeb class BY Laohyx
	此程序在python 2.6/2.7 下测试通过。
	主要是MyWeb.get  .post比较有用，其他的请随意发挥。
	
	版权所有，任何人可以修改，复制，传播，但必须注明原作者
	欢迎交流
	contact:
		Email:laohyx@163.com

'''


class MyHTMLParser(HTMLParser.HTMLParser):
    def __init__(self):
        HTMLParser.HTMLParser.__init__(self)
        self.elements = []
    def parse(self,html):
        self.elements = []
        self.feed(html)
    def handle_starttag(self, tag, attrs):
        # 这里重新定义了处理开始标签的函数
        attrs.append(("tag",tag))
        self.elements.append(attrs)
    def getElements(self,tag = ""):
        if tag == "":
            return self.elements
        return_ele = []
        for ele in self.elements:
            if ele[len(ele) - 1][1] == tag:
                return_ele.append(ele)
        return return_ele


class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor):
  def http_error_110(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_403(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_404(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_400(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_500(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_501(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_502(self, req, fp, code, msg, hdrs): 
    return fp
  def http_error_503(self, req, fp, code, msg, hdrs): 
    return fp
class MyWeb():
    def __init__(self):
        self.cookie = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(NoExceptionCookieProcesser(self.cookie))
        self.opener.addheaders = [('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)')]
        self.html = ""
        self.HTMLParser = MyHTMLParser()
        self._fed = 0
    def post(self,url,postfeild = {}):
        params = urllib.urlencode(postfeild)
        response = self.opener.open(urllib2.Request(url,params))
        self.html = response.read()
        self._fed = 0

        return self.html
    def postfile(self,url,postfeild = ""):
		data = {'name': 'value','file':  postfeild}
		response = urllib2.urlopen(url, data)
		self.html = response.read()
	
	
		return self.html
		
    def get(self,url,feild = {}):
        params = urllib.urlencode(feild)
        if(len(params) > 0):
            url = url + "?" + params
        response = self.opener.open(urllib2.Request(url))
        self.html = response.read()
        self._fed = 0
        return self.html
    def elements(self,tag = ""):
        if self._fed == 0:
            self.HTMLParser.parse(self.html)
            self._fed = 1
        return self.HTMLParser.getElements(tag)
    def getAttribute(self,element,attribute):
        for a,v in element:
            if a == attribute:
                return v
        return ""
    def getElementById(self,id):
        for ele in self.elements(""):
            for a,v in ele:
                if a == "id" and v == id:
                    return ele
        return False
    
def unescape(s):
    s = s.replace("&lt;", "<")
    s = s.replace("&gt;", ">")
    # this has to be last:
    s = s.replace("&amp;", "&")
    return s
    
def main():
    web = MyWeb()
    web.get("http://electsys0.sjtu.edu.cn/edu")
    print web.getElementById("__VIEWSTATE")
if __name__  == "__main__":
    main()
